﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MovieCollectionManager.DataModel;
using System.IO;

namespace MovieCollectionManager
{
    public partial class EditForm : Form
    {
        private int lastMovieIndex;

        public EditForm()
        {
            InitializeComponent();
        }

        private void EditForm_Load(object sender, EventArgs e)
        {
            lastMovieIndex = 0;
            BindMovies();
        }

        private void BindMovies()
        {
            using (var db = new MovieCollectionConteiner())
            {
                List<Movie> movies = db.Movies.ToList();
                comboBoxMovieList.DataSource = movies;
                comboBoxMovieList.DisplayMember = "Title";
                comboBoxMovieList.ValueMember = "Id";
            }
            if (comboBoxMovieList.Items.Count != 0)
                comboBoxMovieList.SelectedIndex = lastMovieIndex;
        }

        private void comboBoxMovieList_SelectedIndexChanged(object sender, EventArgs e)
        {
            int selectedIndex = comboBoxMovieList.SelectedIndex;
            ChangeMovieInfo(selectedIndex);
        }

        private void ChangeMovieInfo(int index)
        {
            Movie selectedMovie = (Movie)comboBoxMovieList.Items[index];
            textBoxTitle.Text = selectedMovie.Title;
            numericUpDownRate.Value = Convert.ToDecimal(selectedMovie.Rate);
            comboBoxType.SelectedItem = selectedMovie.Type;
            numericUpDownDate.Value = selectedMovie.ReleaseDate;
            numericUpDownLength.Value = selectedMovie.Length;
            textBoxDescription.Text = selectedMovie.Description;

            SetPictureBoxImage(selectedMovie);
        }

        private void SetPictureBoxImage(Movie selectedMovie)
        {
            byte[] imagemEmBytes = selectedMovie.BoxArt;
            MemoryStream memoryStream = new MemoryStream(imagemEmBytes, 0, imagemEmBytes.Length);
            memoryStream.Write(imagemEmBytes, 0, imagemEmBytes.Length);

            if (imagemEmBytes.Count() != 0)
                pictureBoxArt.Image = Image.FromStream(memoryStream, true);
            else pictureBoxArt.Image = null;

            memoryStream.Close();
        }

        private void pictureBoxArt_Click(object sender, EventArgs e)
        {
            try
            {
                openFileDialog.ShowDialog();
                if ((!string.IsNullOrEmpty(openFileDialog.FileName)))
                {
                    FileStream fileStream = new FileStream(openFileDialog.FileName, FileMode.Open, FileAccess.Read);
                    pictureBoxArt.Image = Image.FromStream(fileStream);
                    fileStream.Close();
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Imagem não é válida.", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
                openFileDialog.FileName = "";
            }
        }

        private void buttonRemoveImage_Click(object sender, EventArgs e)
        {
            pictureBoxArt.Image = null;
        }

        private void buttonUpdate_Click(object sender, EventArgs e)
        {
            if (comboBoxMovieList.Items.Count == 0)
                return;

            if (textBoxTitle.Text == "")
            {
                MessageBox.Show("O filme deve possuir um título.", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            using (var db = new MovieCollectionConteiner())
            {
                Movie movieToUpdate = (from movie in db.Movies
                                       where movie.Id == (int)comboBoxMovieList.SelectedValue
                                       select movie).First();

                movieToUpdate.Title = textBoxTitle.Text;
                movieToUpdate.Rate = Convert.ToDouble(numericUpDownRate.Value);
                movieToUpdate.Type = comboBoxType.Text;
                movieToUpdate.ReleaseDate = Convert.ToInt32(numericUpDownDate.Value);
                movieToUpdate.Length = Convert.ToInt32(numericUpDownLength.Value);
                movieToUpdate.Description = textBoxDescription.Text;

                if (!string.IsNullOrEmpty(openFileDialog.FileName))
                {
                    byte[] imageBytes = GetBytesOfImage();
                    movieToUpdate.BoxArt = imageBytes;
                }
                else if (pictureBoxArt.Image == null)
                {
                    pictureBoxArt.Image = null;
                    movieToUpdate.BoxArt = new byte[0];
                }

                db.SaveChanges();
            }

            lastMovieIndex = comboBoxMovieList.SelectedIndex;
            BindMovies();
            MessageBox.Show("Filme Atualizado!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private byte[] GetBytesOfImage()
        {
            FileStream fileStream = new FileStream(openFileDialog.FileName, FileMode.Open);
            BinaryReader binaryReader = new BinaryReader(fileStream);
            byte[] imageBytes = binaryReader.ReadBytes(Convert.ToInt32(fileStream.Length));
            fileStream.Close();
            binaryReader.Close();
            return imageBytes;
        }

        private void buttonBack_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}
